package com.hanhai.zrb.backend.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hanhai.common.cache.Cache;
import com.hanhai.common.consts.GlobalConst;
import com.hanhai.common.util.AES;
import com.hanhai.common.util.BasePropertyConfigurer;
import com.hanhai.common.util.CookieWrapper;
import com.hanhai.common.util.MD5Util;
import com.hanhai.common.web.controller.BaseController;
import com.hanhai.zrb.backend.admin.dao.mybatis.BackUserDao;
import com.hanhai.zrb.backend.admin.dao.mybatis.PrivilegeDao;
import com.hanhai.zrb.backend.admin.model.BackendUser;
import com.hanhai.zrb.backend.admin.model.Privilege;
import com.hanhai.zrb.backend.util.BackendLoginUtil;
import com.hanhai.zrb.backend.web.form.LoginForm;

@Controller
public class LoginController extends BaseController {

	@Resource
	private Cache loginCache;

	@Resource
	private BackUserDao backUserDao;
	@Resource
	private PrivilegeDao privilegeDao;
	
	@RequestMapping(value = "/login")
	public String login(String backUrl, Model model,
			HttpServletRequest request, HttpServletResponse response) {
		model.addAttribute("backUrl", backUrl);
		return "/login/login";
	}

	@RequestMapping(value = "/dologin")
	public void doLogin(@Valid LoginForm loginForm, Errors errors,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (errors.hasErrors()) {
			super.jsonFail(response, "用户名或密码错误");
			return;
		}
		BackendLoginUtil.setCurrentUser(null);
		boolean pass = checkPwd(loginForm.getName(), loginForm.getPassword());
		if (pass) {
			BackendUser user = BackendLoginUtil.getCurrentUser();
			initAutoLogin(loginForm, user);
			loginCookie(user, response);
			super.jsonSucceed(response);
			return;
		}
		super.jsonFail(response, "用户名或密码错误");
		return;

	}

	public void initAutoLogin(LoginForm loginForm, BackendUser user) {
		// 保持登录
		boolean autoLogin = false;
		if (loginForm.getAutoLogin() != null
				&& loginForm.getAutoLogin().equals(1)) {
			autoLogin = true;
		}
		user.setAutoLogin(autoLogin);
	}

	private void loginCookie(BackendUser user, HttpServletResponse response)
			throws Exception {
		initPermition(user);
		String key = AES.Encrypt(user.getId() + "",
				GlobalConst.BACKEND_AES_KEY);
		String p2pDomainName = BasePropertyConfigurer
				.getContextProperty(GlobalConst.ZHAORONGBAO_DOMAIN);
	
		int timeout = BackendLoginUtil.timeout(user.getAutoLogin());
		int expire =BackendLoginUtil.expire(user.getAutoLogin());
		CookieWrapper.setCookie(response, GlobalConst.BackendCookieName, key,
				p2pDomainName, expire);
		loginCache.add(key, user, timeout);
	}

	private void initPermition(BackendUser user) {
		Long uid = user.getId();
		List<Privilege> privilegeList=privilegeDao.listAllPrivilege(uid,false);
		List<String> permitList =  new ArrayList<String>();
		if(privilegeList != null && privilegeList.size()>0){
			for(Privilege privilege:privilegeList){
				permitList.add(privilege.getEnname());
			}
		}
		user.setPermitList(permitList);
	}

	private boolean checkPwd(String name, String password) {
		BackendUser user = backUserDao.findByLoginNameForLogin(name);
		String checkPwd = MD5Util.sha1(password);
		if (user != null && StringUtils.equals(user.getPassword(), checkPwd)) {
			BackendLoginUtil.setCurrentUser(user);
			return true;
		}
		return false;
	}

	@RequestMapping(value = "/logout")
	public String logout(String backUrl, Model model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String value = CookieWrapper.getCookieValue(request,
				GlobalConst.BackendCookieName);
		String name = AES.Decrypt(value, GlobalConst.BACKEND_AES_KEY);
		String p2pDomainName = BasePropertyConfigurer
				.getContextProperty(GlobalConst.ZHAORONGBAO_DOMAIN);
		CookieWrapper.clearCookie(response, GlobalConst.BackendCookieName,
				p2pDomainName);
		if (loginCache.exists(name)) {
			loginCache.delete(name);
		}

		return "/login/login";
	}

}
